package cn.com.nes.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;

import static cn.com.nes.common.util.HttpUtils.sendPost;

public class MapUtil {
    /**
     * 通过经纬度获取城市信息
     * @param log, lat
     * @return {"businessAreas":[{"name":"城南","location":"116.244669,40.202981","id":"110114"}],"country":"中国","province":"北京市","citycode":"010","city":[],"adcode":"110114","streetNumber":{"number":"17号","distance":"0.235909","street":"白浮泉路","location":"116.258324,40.205472","direction":"西"},"towncode":"110114005000","district":"昌平区","neighborhood":{"name":[],"type":[]},"township":"城南街道","building":{"name":[],"type":[]}}
     */
    public static JSONObject getCityName(String log, String lat) {
        if (StrUtil.isBlank(log) || StrUtil.isBlank(lat)) {
            return null;
        }
        if (Double.parseDouble(log) == 0 || Double.parseDouble(lat) == 0) {
            return null;
        }
        StringBuffer s = new StringBuffer();
        s.append("key=").append(Globals.Map_Key).append("&location=").append(log)
                .append(",").append(lat);
        String res = HttpUtils.sendJSONPost("https://restapi.ama" +
                "p.com/v3/geocode/regeo", s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            JSONObject regeocode = jsonObject.getJSONObject("regeocode");
            return regeocode.getJSONObject("addressComponent");
        }
        return null;
    }

    public static JSONObject getGeoByAddress(String address, String code) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(Globals.Map_Key).append("&address=").append(address);
        //city参数可指定城市的中文（如北京）、指定城市的中文全拼（beijing）、citycode（010）、adcode（110000），不支持县级市
        if (StrUtil.isNotBlank(code)) {
            code = code.substring(0, 6);
            s.append("&city=").append(code);
        }
        String res = sendPost("https://restapi.amap.com/v3/geocode/geo", s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            if (geocodes != null && geocodes.size() > 0) {
                JSONObject geocode = geocodes.getJSONObject(0);
                String adcode = geocode.getString("adcode");
                adcode = StrUtil.fill(adcode, '0', 12, false);
                geocode.put("adcode", adcode);
                String location = geocode.getString("location");
                String[] lngLat = location.split(",");
                String lng = "";
                String lat = "";
                if (lngLat.length == 2) {
                    lng = lngLat[0];
                    lat = lngLat[1];
                }
                geocode.put("lng", lng);
                geocode.put("lat", lat);
                return geocode;
            }
        }
        return null;
    }
    /**
     * 通过地址获取地理信息
     * @param address
     * @return {"count":"1","infocode":"10000","geocodes":[{"country":"中国","formatted_address":"北京市朝阳区定福庄西里|1号","city":"北京市","adcode":"110105","level":"门牌号","building":{"name":[],"type":[]},"number":[],"province":"北京市","citycode":"010","street":[],"district":"朝阳区","location":"116.553135,39.912972","neighborhood":{"name":[],"type":[]},"township":[]}],"status":"1","info":"OK"}
     */
    public static JSONObject getGeoByAddress(String address) {
        StringBuffer s = new StringBuffer();
        s.append("key=").append(Globals.Map_Key).append("&address=").append(address);
        String res = sendPost("https://restapi.amap.com/v3/geocode/geo", s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        //System.out.println(jsonObject);
        if ("1".equals(status)) {
            JSONArray geocodes = jsonObject.getJSONArray("geocodes");
            if (geocodes != null && geocodes.size() > 0) {
                JSONObject geocode = geocodes.getJSONObject(0);
                String adcode = geocode.getString("adcode");
                adcode = StrUtil.fill(adcode, '0', 12, false);
                geocode.put("adcode", adcode);
                String location = geocode.getString("location");
                String[] lngLat = location.split(",");
                String lng = "";
                String lat = "";
                if (lngLat.length == 2) {
                    lng = lngLat[0];
                    lat = lngLat[1];
                }
                geocode.put("lng", lng);
                geocode.put("lat", lat);
                return geocode;
            }
        }
        return null;
    }

    /**
     * 通过经纬度获取详细地址
     * @param log, lat
     * @return 北京市昌平区城南街道白浮泉路17号
     */
    public static String getAddress(String log, String lat) {
        if (StrUtil.isBlank(log) || StrUtil.isBlank(lat)) {
            return null;
        }
        if (Double.parseDouble(log) == 0 || Double.parseDouble(lat) == 0) {
            return null;
        }
        StringBuffer s = new StringBuffer();
        s.append("key=").append(Globals.Map_Key).append("&location=").append(log)
                .append(",").append(lat);
        String res = HttpUtils.sendJSONPost("https://restapi.amap.com/v3/geocode/regeo", s.toString());
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            JSONObject regeocode = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent");
            String province = regeocode.getString("province");
            String city = regeocode.getString("city");
            String district = regeocode.getString("district");
            String township =regeocode.getString("township");;
            String street =((JSONObject)regeocode.getJSONObject("streetNumber")).getString("street");
            String number =((JSONObject)regeocode.getJSONObject("streetNumber")).getString("number");
            StringBuilder str = new StringBuilder("");
            str.append(province);
            if (!"[]".equals(city)) str.append(city);
            str.append(district);
            str.append(township);
            str.append(street);
            str.append(number);
            return str.toString();
        }
        return null;
    }

    public static JSONObject getGeoByLocation(String location) {
        //https://restapi.amap.com/v3/geocode/regeo?key=1dda12723a3d917025e1f98e1ae5a8e9&location=116.481488,39.990464&radius=5000&extensions=all&batch=false&roadlevel=0
        StringBuffer s = new StringBuffer();
        s.append("key=").append(Globals.Map_Key).append("&location=").append(location).append("&poitype=&radius=1000&extensions=base&batch=false&roadlevel=1");
        String res = sendPost("https://restapi.amap.com/v3/geocode/regeo", s.toString());
        if(StringUtils.isEmpty(res)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            JSONObject geocode = jsonObject.getJSONObject("regeocode");
            if (geocode != null) {
                geocode = geocode.getJSONObject("addressComponent");
                String adcode = geocode.getString("adcode");
                adcode = StrUtil.fill(adcode, '0', 12, false);
                geocode.put("adcode", adcode);
                return geocode;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        final JSONObject c = MapUtil.getGeoByAddress("北京市朝阳区");
        System.out.println(c.toJSONString());

        //JSONObject cityInfo = getCityName("116.258321", "40.205472");
        //System.out.println(cityInfo.toJSONString());

        //String str = getAddress("116.258321", "40.205472");
        //System.out.println(str);
    }
}
